using System;
using System.Collections;

namespace Microsoft.Samples.Windows.Forms.Navigation
{
	/// <summary>
	/// A back or forward stack for a navigation frame.
	/// </summary>
	/// <remarks>
	/// This class extends Stack to provide direct access to the text (titles)
	/// of pages stored on the stack without having to expose the stack's contents
	/// directly.
	/// </remarks>
	internal class NavigationStack : Stack
	{
		/// <returns>
		/// The titles for the pages on the stack, starting at the top of the stack.
		/// </returns>
		/// <remarks>
		/// This may return different results than obtaining the pages on the stack
		/// with the Pages property and asking the resulting pages what their titles
		/// are. Such an approach would return the current value of the page titles.
		/// Instead, the present property returns the titles of the pages at the
		/// time the page was pushed on the stack. Such a list is appropriate for
		/// display on a dropdown menu of pages for a Back and Forward button, because
		/// it shows the titles the user can remember seeing.
		/// </remarks>
		/// <param name="maximumPageTitleCount">If greater than zero, the maximum
		/// number of page titles that will be returned</param>
		public string[] GetPageTitles(int maximumPageTitleCount)
		{
			if (Count == 0)
			{
				// An empty stack has no page titles.
				return null;
			}

			// Determine how many page titles we'll actually get.
			int titleCount;
			if (maximumPageTitleCount > 0 && Count > maximumPageTitleCount)
			{
				titleCount = maximumPageTitleCount;
			}
			else
			{
				titleCount = Count;
			}
		
			// Collect the page titles.
			ArrayList pageTitles = new ArrayList(titleCount);
			foreach (NavigationContext context in this)
			{
				pageTitles.Add(context.PageText);
				if (pageTitles.Count >= titleCount)
				{
					// We've collected all the page titles we need.
					break;
				}
			}

			// Convert the list of page titles to an array.
			string[] pageTitleArray = null;
			if (pageTitles.Count > 0)
			{
				pageTitleArray = new string[pageTitles.Count];
				pageTitles.CopyTo(pageTitleArray);
			}

			return pageTitleArray;
		}
	}
}
